package com.yuncheng.oaApi.FlowController;


import com.yuncheng.entity.YcSysUser;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaLogConstant;
import com.yuncheng.oaApi.constant.OaBgypsqglOaFlowConstants;
import com.yuncheng.oaApi.constant.OaFlowConstant;
import com.yuncheng.oaApi.vo.OaBgypsqglVo;
import com.yuncheng.oaApi.vo.OaFlowVo;
import com.yuncheng.oaApi.vo.OaReturnVo;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.oaApi.FlowService.NewOaBgypsqglOaFlowService;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.busService.MyLcFlowService;
import com.yuncheng.oaApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.oaApi.mapper.OaBgypsqglFlowMapper;
import com.yuncheng.oaApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.oaApi.utils.GetUuIdUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Api(tags = "New_OA-办公用品申请管理")
@RestController
@RequestMapping("/api/spzx-oa/newflow-bgyp")
public class NewOaBgypglFlowController {
    private static final Logger log = LoggerFactory.getLogger(NewOaBgypglFlowController.class);


    @Resource
    private OaBgypsqglFlowMapper oaBgypsqglFlowMapper;

    @Resource
    private NewOaBgypsqglOaFlowService newOaBgypsqglFlowService;

    @Resource
    private IOaBgypsqglService oaBgypsqglService;

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private IOaSysTzMessageService sysTzMessageService;

    @Resource
    @Lazy
    private MyLcFlowService myLcFlowService;

    @Resource
    @Lazy
    private IOaProcessBusinessService oaProcessBusinessService;


    @Resource
    @Lazy
    private IOaYcSysUserService ycSysUserService;

    @Resource
    @Lazy
    private IOaBgypghjlService oaBgypghjlService;

    @Resource
    @Lazy
    private IOaBgypsxmxxxService oaBgypsxmxxxService;

    /**
     * 流程列表分页查询
     *
     * @param oaBgypsqglVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(
            OaBgypsqglVo oaBgypsqglVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser){
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaBgypsqglVo> page = new Page<>(pageNo, pageSize);
        oaBgypsqglVo.setFlcmc(OaFlowConstant.OA_BGYPSQLC_NAME);

        IPage<OaBgypsqglVo> list = null;
        if (StringUtils.isNotBlank(oaBgypsqglVo.getOaid())){
            OaBgypsqgl xzswsp = oaBgypsqglService.getById(oaBgypsqglVo.getOaid());
            if (xzswsp != null){
                list = oaBgypsqglFlowMapper.flowJkPage(page,onlyCurrentUser,user,oaBgypsqglVo);
            }
        }
        return HttpResult.ok(list);
    }


    /**
     * 流程列表分页查询
     * @param oaBgypsqglVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程列表-分页查询")
    @ApiOperation(value = "流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(
            OaBgypsqglVo oaBgypsqglVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser){
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        if (StringUtils.isBlank(oaBgypsqglVo.getFblzt())) {
            oaBgypsqglVo.setFblzt(OaCommonFlowConstant.BLZT_DB);
        }
        Page<OaBgypsqglVo> page = new Page<>(pageNo, pageSize);
        oaBgypsqglVo.setFlcmc(OaFlowConstant.OA_BGYPSQLC_NAME);
        IPage<OaBgypsqglVo> list = oaBgypsqglFlowMapper.flowJobPage(page, onlyCurrentUser, user, oaBgypsqglVo);
        return HttpResult.ok(list);
    }

    /**
     * 我的已办
     */
    @AutoLog(value = "流程列表-我的已办")
    @ApiOperation(value = "流程列表-我的已办")
    @GetMapping("myJobPage")
    public HttpResult<?> myJobPage(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            OaBgypsqglVo oaBgypsqglVo) {

        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaBgypsqglVo> page = new Page<>(pageNo, pageSize);
        IPage<OaBgypsqglVo> list = oaBgypsqglFlowMapper.myYbFlowPage(page, true, user, oaBgypsqglVo);
        return HttpResult.ok(list);
    }


    @AutoLog(value = "办公用品申请管理流程")
    @ApiOperation(value = "办公用品申请管理流程")
    @PostMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestBody OaBgypsqgl oaBgypsqgl) throws InvocationTargetException, IllegalAccessException {
        String oaid = "";
        //当前人的id
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        if (StringUtils.isNotBlank(oaBgypsqgl.getId())){
            OaBgypsqgl oaids = oaBgypsqglService.getById(oaBgypsqgl.getId());
            oaid = oaBgypsqgl.getId();


            ConvertUtils.register(new DateConvert(), Date.class);
            try {
                BeanUtils.populate(oaids,BeanUtils.describe(oaBgypsqgl));
            } catch (IllegalAccessException e) {
                log.error("出错-保存事项【非法访问异常】,{}",e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("出错-保存事项【调用TargetException】,{}",e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("出错-找不到可用方法",e.getMessage());
            }
            oaBgypsqglService.updateById(oaids);

        }else {


            oaid = GetUuIdUtils.ReplaceUuId();
            oaBgypsqgl.setId(oaid);
            oaBgypsqgl.setFuserid(currentUser.getId());
            oaBgypsqgl.setFlyr(currentUser.getName());
            oaBgypsqgl.setFlyks(currentUser.getDeptName());
            oaBgypsqgl.setFlyrq(DateConversionUtils.DateToYMDHMSChineseString(new Date()));


            oaBgypsqglService.save(oaBgypsqgl);
        }
        /**
         * @Author: lhb
         * @Description : 是否发起流程   如果是开始申请就跳转流程
         *               在这里设置 nextNodeName 指定下个环节节点 做当前跳转流程的判断，然后设置变量接收环节的值，写到nextNodeName中
         * @DateTime:
         * @Params: Fsffqlc
         */
        String msg = "保存成功";
        String lcmbCode = OaFlowConstant.OA_BGYPSQ;

        OaJobEntity job = new OaJobEntity();
        // 初始化流程
        Result result = newOaBgypsqglFlowService.createProcess(lcmbCode,oaid, currentUser);
        //做一次规则校验 如果查到此oaid 在表中已经插入 那就执行更新

        List<OaProcessBusiness> oaProcessBusinessList = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        OaBgypsqgl oaBgypsqgl1 = oaBgypsqglService.getById(oaid);
        List<OaBgypsxmxxx> oaBgypsxmxxxes = oaBgypsxmxxxService.list(new LambdaQueryWrapper<OaBgypsxmxxx>()
                .eq(OaBgypsxmxxx::getFsqid, oaid));
        List list = new ArrayList();
        if (CollectionUtils.isNotEmpty(oaBgypsxmxxxes)){
            for (OaBgypsxmxxx oaBgypsxmxxxe:oaBgypsxmxxxes){
                list.add(oaBgypsxmxxxe.getFsqmc());
            }
        }
        String bt = currentUser.getName()+"提交的办公用品/设备申请"; //标题
        String zy = "领用日期:["+ oaBgypsqgl1.getFlyrq()+"]"+"\n"
                +"领用科室:["+ oaBgypsqgl1.getFlyks() + "]"+"\n"
                + "领用物品名称:"+ list;

        if (oaProcessBusinessList.size() == 0){
            //初始化的时候 像 流程业务主表添加拼接初始化数据
            oaProcessBusinessService.addProcess(oaid,zy,bt,lcmbCode,OaFlowConstant.OA);

        }else {
            String id = oaProcessBusinessList.get(0).getId();  //当前已经插入的主键id 然后更新 摘要信息
            OaProcessBusiness oaProcessBusiness = oaProcessBusinessService.getById(id);
            oaProcessBusiness.setFzy(zy);
            oaProcessBusinessService.updateById(oaProcessBusiness);

        }
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }else {
           job = (OaJobEntity)result.getResult();
            if (job != null) {
                // 是否提交流程
                if (StringUtils.isNotBlank(oaBgypsqgl1.getFsffqlc()) && oaBgypsqgl1.getFsffqlc().equals(OaCommonFlowConstant.SFFQLC_YES)) {



                    Result result1 = newOaBgypsqglFlowService.passJob(oaid, job.getId(), "同意", "", "");
                    if (!result1.isSuccess()) {
                        return HttpResult.error(result.getMessage());
                    }
                    //提交完成后 更新待办信息
                    sysTzMessageService.tjMessage(oaid);
                    List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                            .eq(OaProcessBusiness::getFpid, oaid));
                    OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
                    OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());
                    byId1.setFsfkch(0);
                    byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
                    oaProcessBusinessService.updateById(byId1);

                    myLcFlowService.recall(oaid);
                    msg = "提交成功";
                }
            }
        }
        HashMap map = new HashMap();
        map.put("msg",msg);
        map.put("oaMap",oaBgypsqgl);
        map.put("jobMap",job);

        return HttpResult.ok(map);

    }

    /**
     * 办公用品申请管理流程保存
     */
    @AutoLog(value = "办公用品申请管理流程保存")
    @ApiOperation(value = "办公用品申请管理流程保存")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SAVE; // 保存
        String jobId = oaFlowVo.getJobid(); // 当前流程任务id
        String oaid = oaFlowVo.getOaid(); // 当前办公主键id
        String opinion = oaFlowVo.getOpinion(); // 办理意见


        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }

        // 流程处理
        Result httpResult = newOaBgypsqglFlowService.handleFlow(oaFlowVo, null, jobId, oaid, submitType, opinion);
        if (!httpResult.isSuccess()){
            return HttpResult.error(httpResult.getMessage());
        }

        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");

        res.setResult(map);
        return res;
    }

    /**
     * 办公用品申请管理流程提交
     */
    @AutoLog(value = "办公用品申请管理流程提交")
    @ApiOperation(value = "办公用品申请管理流程提交")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = oaFlowVo.getJobid();
        String oaid = oaFlowVo.getOaid();
        String opinion = oaFlowVo.getOpinion();
        OaBgypsqgl oaId = oaBgypsqglService.getById(oaid);
        OaJobEntity jobid = spcySqsxJobService.getById(jobId);

        if (jobid.getFhjmc().equals(OaBgypsqglOaFlowConstants.HJMC_BGSQR)) {

        } else {
            oaId.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
        }
        if (StringUtils.isBlank(oaId.getFsffqlc())) {
            oaId.setFsffqlc(OaCommonFlowConstant.SFFQLC_YES);
        }

        List<OaBgypsxmxxx> oaBgypsxmxxxes = oaBgypsxmxxxService.list(new LambdaQueryWrapper<OaBgypsxmxxx>()
                .eq(OaBgypsxmxxx::getFsqid, oaid));
        if (CollectionUtils.isNotEmpty(oaBgypsxmxxxes)){
            for (OaBgypsxmxxx oaBgypsxmxxxe:oaBgypsxmxxxes){
                String fsqmc = oaBgypsxmxxxe.getFsqmc();
                if (StringUtils.isBlank(fsqmc)){
                    throw new BusinessException("申请名称为空");
                }
            }
        }


        //更新申请摘要数据
        List<OaProcessBusiness> oaProcessBusinessList = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));

        OaBgypsqgl oaBgypsqgl1 = oaBgypsqglService.getById(oaid);
        List list = new ArrayList();
        if (CollectionUtils.isNotEmpty(oaBgypsxmxxxes)){
            for (OaBgypsxmxxx oaBgypsxmxxxe:oaBgypsxmxxxes){
                list.add(oaBgypsxmxxxe.getFsqmc());
            }
        }
        String zy = "领用日期:["+ oaBgypsqgl1.getFlyrq()+"]"+"\n"
                +"领用科室:["+ oaBgypsqgl1.getFlyks() + "]"+"\n"
                + "领用物品名称:"+ list;

        String id = oaProcessBusinessList.get(0).getId();  //当前已经插入的主键id 然后更新 摘要信息
            OaProcessBusiness oaProcessBusiness = oaProcessBusinessService.getById(id);
            oaProcessBusiness.setFzy(zy);
            oaProcessBusinessService.updateById(oaProcessBusiness);





        oaBgypsqglService.updateById(oaId);

        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/

        OaJobEntity nowJob = null;

        Result httpResult1 = newOaBgypsqglFlowService.handleFlow(oaFlowVo, nowJob, jobId, oaid, submitType, opinion);
        if (!httpResult1.isSuccess()){
            return HttpResult.error(httpResult1.getMessage());
        }
        List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        OaProcessBusiness oaProcessBusinesss = oaProcessBusinessList1.get(0);
        OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusinesss.getId());
        byId1.setFsfkch(0);
        byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
        oaProcessBusinessService.updateById(byId1);
        //提交完成后 更新待办信息
        sysTzMessageService.tjMessage(oaid);
        myLcFlowService.recall(oaid);
        return HttpResult.ok("提交成功");
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @AutoLog(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid", name = "流程任务id", required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid") String jobid) {
        if (StringUtils.isBlank(jobid)) {
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = newOaBgypsqglFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }

    /**
     * 获取已办列表-通过当前流程id-自定义退回
     *
     * @param jobid
     * @return
     */
    @AutoLog(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiOperation(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid", value = "流程任务id"),
            @ApiImplicitParam(name = "isZdhj", value = "是否指定环节，默认：true，指定")
    })
    @GetMapping(value = "queryAllYbJob")
    public HttpResult<?> queryAllYbJob(@RequestParam(value = "jobid", defaultValue = "") String jobid,
                                       @RequestParam(value = "isZdhj", defaultValue = "true") boolean isZdhj) {
        List<Map<String, String>> currentJobPrevious = newOaBgypsqglFlowService.getCurrentJobPrevious(jobid, isZdhj);
        return HttpResult.ok(currentJobPrevious);
    }

    /**
     * 退回环节
     *
     * @return
     */
    @AutoLog(value = "自定义-退回环节")
    @ApiOperation(value = "自定义-退回环节")
    @PostMapping(value = "returnUpperzdyFlowJob")
    public HttpResult<?> returnUpperzdyFlowJob(@RequestBody OaReturnVo oaReturnVo) {
        newOaBgypsqglFlowService.returnZdJob(oaReturnVo);
        return HttpResult.ok("退回成功");
    }

    @AutoLog(value = "删除办公用品申请流程")
    @ApiOperation(value = "删除办公用品申请流程")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobids", value = "流程任务id,逗号分割", required = true)
    })
    @DeleteMapping(value = "deleteGwycFlowJob")
    public HttpResult<?> deleteGwycFlowJob(@RequestParam("jobids") String jobids) {
        if (StringUtils.isBlank(jobids)) {
            return HttpResult.error("参数不能为空");
        }
        List<String> jobIdList = Arrays.asList(jobids.split(","));
        String logNr = "";
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(jobIdList)){
            List<OaJobEntity> jobList = spcySqsxJobService.listByIds(jobIdList);
            if (CollectionUtils.isNotEmpty(jobList)){
                for (OaJobEntity job : jobList) {
                    spcySqsxJobService.removeById(job.getId());
                    OaBgypsqgl oaBgypsqgl = oaBgypsqglService.getById(job.getFpid());
                    if (oaBgypsqgl != null) {
                        oaBgypsqglService.removeById(job.getFpid());

                        logNr = "删除申请办公用品流程" + job.getFhjmc() + ": ";
                        map = ObjectToMapUtils.objectToMap(oaBgypsqgl);
                        logNr += LogUtils.MapToStringMethod(map);

                        spcyLogService.addLogs(job.getFhjmc(), logNr, job.getFpid(), OaLogConstant.LOGS_OA_GWYC, OaCommonFlowConstant.LOGS_SYS_TYPE_SC);
                    }
                }
            }
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 修改使用人
     */
    @Log
    @AutoLog(value = "修改使用人")
    @ApiOperation(value = "修改使用人")
    @PutMapping(value = "updateYhr")
    public HttpResult<?> updateYhr(@RequestBody OaBgypsxmxxx oaBgypsxmxxx) {
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        String userid = oaBgypsxmxxx.getFsyrid();
        YcSysUser sysUser = ycSysUserService.getById(userid);

        String realname = sysUser.getRealname();
        String orgName = sysUser.getOrgName();
        oaBgypsxmxxx.setFsyr(realname);
        oaBgypsxmxxx.setFsyrid(userid);
        oaBgypsxmxxx.setFsyrks(orgName);
        oaBgypsxmxxxService.updateById(oaBgypsxmxxx);

        String nodename = OaFlowConstant.OA_BGYPSQLC_NAME;
        String logNr = currentUser.getName() + "修改使用人为:" + realname;
        spcyLogService.addLogs(nodename,logNr,oaBgypsxmxxx.getId(), OaLogConstant.LOGS_OA_BGYPSQ, OaCommonFlowConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok();

    }

    /**
     * 归还办公用品
     */
    @Log
    @AutoLog(value = "归还办公用品")
    @ApiOperation(value = "归还办公用品")
    @GetMapping(value = "updategh")
    public HttpResult<?> updategh(OaBgypghjl oaBgypghjl) {
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        //查看自己申请的物品列表，归还需要归还的物品。使用id


        if (StringUtils.isBlank(oaBgypghjl.getFghsl())){
            throw new BusinessException("归还数量为空");
        }


        if (StringUtils.isBlank(oaBgypghjl.getFpid())){
            throw new BusinessException("申请事项id为空");
        }
        OaBgypsxmxxx oaBgypsxmxxx = oaBgypsxmxxxService.getById(oaBgypghjl.getFpid());
        YcSysUser sysUser = ycSysUserService.getById(currentUser.getId());

        //查询申请的数量，然后循环当前id的归还数量看看是否全部归还完成
        if (oaBgypsxmxxx != null){
            Integer fsl = oaBgypsxmxxx.getFsqsl();
            Integer fyghsl = 0;

            //添加一个归还记录
            oaBgypghjl.setId(GetUuIdUtils.ReplaceUuId());
            oaBgypghjl.setFwpmc(oaBgypsxmxxx.getFsqmc());
            oaBgypghjl.setFghr(sysUser.getRealname());
            oaBgypghjl.setFghrks(sysUser.getOrgName());
            oaBgypghjl.setFghsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
            oaBgypghjl.setFghsl(oaBgypghjl.getFghsl());
            oaBgypghjlService.save(oaBgypghjl);

            //查询
            List<OaBgypghjl> oaBgypghjlsList = oaBgypghjlService.list(new LambdaQueryWrapper<OaBgypghjl>()
                    .eq(OaBgypghjl::getFpid, oaBgypghjl.getFpid())
                    .eq(OaBgypghjl::getFwpmc, oaBgypsxmxxx.getFsqmc()));

            if (CollectionUtils.isNotEmpty(oaBgypghjlsList)){
                for (OaBgypghjl  oaBgypghjls : oaBgypghjlsList){
                    fyghsl += Integer.valueOf(oaBgypghjls.getFghsl());
                }
               int zghsl =  fyghsl + Integer.valueOf(oaBgypghjl.getFghsl());

                if (fsl > zghsl){
                    oaBgypsxmxxx.setFsfqbgh(OaCommonFlowConstant.BGYPGH_NO);

                } else if (fsl == zghsl) {
                    oaBgypsxmxxx.setFsfqbgh(OaCommonFlowConstant.BGYPGH_YES);
                }else if (fsl < zghsl) {
                    throw new BusinessException("归还数量大于申请数量!");
                }

                oaBgypghjl.setId(GetUuIdUtils.ReplaceUuId());
                oaBgypghjl.setFwpmc(oaBgypsxmxxx.getFsqmc());
                oaBgypghjl.setFghr(sysUser.getRealname());
                oaBgypghjl.setFghrks(sysUser.getOrgName());
                oaBgypghjl.setFghsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
                oaBgypghjl.setFghsl(oaBgypghjl.getFghsl());
                oaBgypghjlService.save(oaBgypghjl);

            }else  {
                if (fsl < Integer.valueOf(oaBgypghjl.getFghsl())) {
                    throw new BusinessException("归还数量大于申请数量!");
                }

                oaBgypghjl.setId(GetUuIdUtils.ReplaceUuId());
                oaBgypghjl.setFwpmc(oaBgypsxmxxx.getFsqmc());
                oaBgypghjl.setFghr(sysUser.getRealname());
                oaBgypghjl.setFghrks(sysUser.getOrgName());
                oaBgypghjl.setFghsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
                oaBgypghjl.setFghsl(oaBgypghjl.getFghsl());
                oaBgypghjlService.save(oaBgypghjl);


            }

           if (StringUtils.isNotBlank(oaBgypsxmxxx.getFghsl())){
               String fghsl = oaBgypsxmxxx.getFghsl();
               int i = Integer.parseInt(fghsl);
               String fghsl1 = oaBgypghjl.getFghsl();
               int i2 = Integer.parseInt(fghsl1);
               int i3 = i + i2;
               oaBgypsxmxxx.setFghsl(String.valueOf(i3));
           }else {
               oaBgypsxmxxx.setFghsl(oaBgypghjl.getFghsl());
           }

            oaBgypsxmxxx.setFghr(currentUser.getName());
            oaBgypsxmxxx.setFghrks(currentUser.getOrgName());
            oaBgypsxmxxxService.updateById(oaBgypsxmxxx);
        }
        oaBgypghjlService.save(oaBgypghjl);

        String nodename = OaFlowConstant.OA_BGYPSQLC_NAME;
        String logNr = currentUser.getName() + "归还:" + oaBgypsxmxxx.getFsqmc()+"，数量为："+oaBgypghjl.getFghsl();
        spcyLogService.addLogs(nodename,logNr,oaBgypghjl.getId(), OaLogConstant.LOGS_OA_BGYPSQ, OaCommonFlowConstant.LOGS_SYS_TYPE_XG);

        return  HttpResult.ok("归还成功");
    }






    @AutoLog(value = "更新申请明细")
    @ApiOperation(value = "更新申请明细")
    @GetMapping(value = "updatesqmx")
    public HttpResult<?> updatesqmx(OaBgypsxmxxx oaBgypsxmxxx) {
        oaBgypsxmxxxService.updateById(oaBgypsxmxxx);

        return HttpResult.ok("修改成功");

    }

    @AutoLog(value = "删除申请明细")
    @ApiOperation(value = "删除申请明细")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "sqmxid", value = "申请明细id", required = true)
    })
    @DeleteMapping(value = "delsqmx")
    public HttpResult<?> delsqmx(@RequestParam("sqmxid") String sqmxid)  {
        if (StringUtils.isNotBlank(sqmxid)) {
            oaBgypsxmxxxService.removeById(sqmxid);
        } else {
            return HttpResult.error("申请明细id不能为空");
        }

        return HttpResult.ok("删除成功");

    }

    /**
     * @param:
     * @Description: 根据oaid查询申请明细
     * @auther: lhb
     * @date: 2023/9/11 15:49
     */
    @AutoLog(value = "根据oaid查询申请明细")
    @ApiOperation(value = "根据oaid查询申请明细")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "oaid", value = "申请id", required = true)
    })
    @GetMapping(value = "selectOaid")
    public HttpResult selectOaid(String oaid) {
        List<OaBgypsxmxxx> list = oaBgypsxmxxxService.list(new LambdaQueryWrapper<OaBgypsxmxxx>().eq(OaBgypsxmxxx::getFsqid, oaid));
        return HttpResult.ok(list);
    }

    @AutoLog(value = "增加申请明细")
    @ApiOperation(value = "增加申请明细")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "sqid", value = "申请id", required = true),
    })
    @PostMapping(value = "addsqmx")
    public HttpResult<?> addsqmx(@RequestBody OaBgypsxmxxx oaBgypsxmxxx)  {
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (StringUtils.isBlank(oaBgypsxmxxx.getFsqid())){
            throw new BusinessException("申请id为空");
        }

        oaBgypsxmxxx.setFsyr(currentUser.getName());
        oaBgypsxmxxx.setFsyrid(currentUser.getId());
        oaBgypsxmxxx.setFsyrks(currentUser.getOrgName());


        oaBgypsxmxxxService.save(oaBgypsxmxxx);

        return HttpResult.ok("新增成功");

    }

    /**
     * 办公用品申请列表
     */
    @AutoLog(value = "办公用品申请列表")
    @ApiOperation(value = "办公用品申请列表")
    @GetMapping(value = "bgypsqList")
    public HttpResult<?> bgypsqList( @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                     OaBgypsxmxxx oaBgypsxmxxx){
        //这个列表查询当前流程结束后的申请列表和申请数量，如果是自己只能查自己，有权限的人查全部

        List<OaBgypsqgl> oaBgypsqgls = oaBgypsqglService.list(new LambdaQueryWrapper<OaBgypsqgl>()
                .eq(OaBgypsqgl::getFlczt, OaCommonFlowConstant.FLOW_LCJS));
        List idlist = new ArrayList();
        if (CollectionUtils.isNotEmpty(oaBgypsqgls)){
            for (OaBgypsqgl oaBgypsqgl:oaBgypsqgls){
                idlist.add(oaBgypsqgl.getId());
            }
            LambdaQueryWrapper<OaBgypsxmxxx> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(OaBgypsxmxxx::getFsqid, idlist);
            queryWrapper.like(StringUtils.isNotBlank(oaBgypsxmxxx.getFsyr()),OaBgypsxmxxx::getFsyr,oaBgypsxmxxx.getFsyr());
            queryWrapper.like(StringUtils.isNotBlank(oaBgypsxmxxx.getFsyrks()),OaBgypsxmxxx::getFsyrks,oaBgypsxmxxx.getFsyrks());
            queryWrapper.like(StringUtils.isNotBlank(oaBgypsxmxxx.getFghr()),OaBgypsxmxxx::getFghr,oaBgypsxmxxx.getFghr());
            queryWrapper.like(StringUtils.isNotBlank(oaBgypsxmxxx.getFghrks()),OaBgypsxmxxx::getFghrks,oaBgypsxmxxx.getFghrks());
            queryWrapper.like(StringUtils.isNotBlank(oaBgypsxmxxx.getFsqmc()),OaBgypsxmxxx::getFsqmc,oaBgypsxmxxx.getFsqmc());

            Page<OaBgypsxmxxx> page = new Page<>(pageNo, pageSize);
            Page<OaBgypsxmxxx> pageList = oaBgypsxmxxxService.page(page, queryWrapper);

            return HttpResult.ok(pageList);
        }else {
            return HttpResult.ok();
        }


    }



}
